public class num51 {
    int count = 0;
    public int reversePairs(int[] nums) {
         mergeinternal(nums,0,nums.length - 1);
         return count;
    }
    private void mergeinternal(int[] nums, int l, int r) {
        if(l >= r) {
            return;
        }
        int mid = l + ((r - l) / 2);
        mergeinternal(nums,l,mid);
        mergeinternal(nums,mid + 1,r);
            merge(nums,l,mid,r);
    }
    private void merge(int[] nums, int l, int mid, int r) {
        int[] aux = new int[r - l + 1];
        for (int i = 0; i < aux.length; i++) {
            aux[i] = nums[i + l];
        }
        int i = l;
        int j = mid + 1;
        for (int k = l; k <= r; k++) {
            if(i == (mid + 1)) {
                nums[k] = aux[j - l];
                j ++;
            }else if(j == (r + 1)) {
                nums[k] = aux[i - l];
                i ++;
            }else if(aux[i - l] <= aux[j - l]) {
                nums[k] = aux[i - l];
                i ++;
            }else {
                nums[k] = aux[j - l];
                count += (mid - i + 1);
                j ++;
            }
        }
    }
}
